package com.yunti.springboot.sql;

import cn.hutool.core.date.DateUtil;
import com.yunti.springboot.email.SendEmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.util.concurrent.TimeUnit;

/**
 * @author yangtt
 * @date 2023/7/5
 */
@Service
@Slf4j
@Component("com_yunti_cloudsportmiddle_DataService")
public class DataService {
    @Value("${spring.datasource.username}")
    String userName;
    @Value("${spring.datasource.password}")
    String pwd;
    @Value("${spring.datasource.url}")
    String url;
    @Value("${spring.web.root.path}")
    String path;

    /**
     * 备份mysql数据库
     *
     * @throws Exception
     */
    @Resource
    SendEmailService service;

    public void dbBackUpMysql(String senders) {
        //mysqldump -h 127.0.0.1 -uroot -proot mysql user >D:/info/server/var/backupdata/backups.sql
        String dbName = "cloud_sport_mid";
        String pathSql = path + DateUtil.format(DateUtil.date(), "yyyy-MM-dd") + "/" + dbName + ".sql";
        log.info(pathSql);
        File fileSql = new File(pathSql);
        File filePath = new File(  path + DateUtil.format(DateUtil.date(), "yyyy-MM-dd"));
        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;

        //设置超时一分钟
        try {
            //创建备份sql文件
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            if (!fileSql.exists()) {
                fileSql.createNewFile();
            }else {
                String time = DateUtil.format(DateUtil.date(), "_HH-mm-ss");
                pathSql = path + DateUtil.format(DateUtil.date(), "yyyy-MM-dd") + "/" + dbName+ time + ".sql";
                fileSql = new File(pathSql);
            }
            //mysqldump -hlocalhost -uroot -p123456 db > /home/back.sql
            StringBuffer sb = new StringBuffer();
            sb.append("mysqldump");
//            sb.append(" -h" + "127.0.0.1");
            sb.append(" -u" + userName);
            sb.append(" -p" + pwd);
            sb.append(" --default-character-set=utf8 " );
            sb.append(" --databases");
            sb.append(" " + dbName + " > ");
            sb.append(pathSql);
            log.info("cmd命令为：" + sb.toString());
            log.info("开始备份：" + dbName);
            Process process = null;
            //判断操作系统 windwos与linux使用的语句不一样
            if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
                process = Runtime.getRuntime().exec("cmd /c " + sb.toString());
            } else if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) {
                process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c" , sb.toString()});
            }

            //设置超时一分钟
            process.waitFor(60000, TimeUnit.MILLISECONDS);
            //输出返回的错误信息
            StringBuffer mes = new StringBuffer();
            String tmp = "";
            BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream(), "gbk"));
            while ((tmp = error.readLine()) != null) {
                mes.append(tmp);
            }
            if (mes != null || !"".equals(mes)) {
                log.info("备份日志!==>" + mes.toString());
            }
            error.close();
//            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8);
//            bufferedReader = new BufferedReader(inputStreamReader);
//            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileSql), StandardCharsets.UTF_8),true);
//            printWriter.println("-- 导入字段过长处理");
//            printWriter.println("set global max_allowed_packet=1024*1024*16;");
//
//            String line;
//            while ((line = bufferedReader.readLine()) != null) {
//                printWriter.println(line);
//            }
//            printWriter.flush();
            log.info("已备份数据库");
            service.sendData(senders,fileSql,DateUtil.format(DateUtil.date(), "yyyy-MM-dd")+"_数据库备份");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
